import { mergeLocalCart, findCartList, insertCart, deleteCart, updateCart, checkAllCart } from '@/api/cart'
// 购物车
export default {
  namespaced: true,
  state: () => ({
    list: []
  }),
  getters: {
    /**
   * 1. 计算有效商品列表=》isEffective = true
   * 2. 计算有效商品的总数量
   * 3. 计算有效商品的总价
   */
    // 有效商品的列表
    effectiveList: state => {
      return state.list.filter(item => item.isEffective)
    },
    // 计算有效商品的总数量
    effectiveListCount: (state, getters) => {
      return getters.effectiveList.reduce((acc, item) => acc + item.count, 0)
    },
    // 计算有效商品的总价
    effectiveListTotal: (state, getters) => {
      return getters.effectiveList.reduce((acc, item) => acc + item.count * item.nowPrice, 0)
    },
    /**
     * 1. 选中的购物车商品数据
     * 2. 选中商品总价
     * 3. 购物车中商品是否时全部选中状态
     */
    selectedEffectiveList: (state, getters) => {
      return getters.effectiveList.filter(item => item.selected)
    },
    selectedEffectiveListTotal: (state, getters) => {
      return getters.selectedEffectiveList.reduce((acc, item) => acc + item.count * item.nowPrice, 0)
    },
    isAll (state, getters) {
      return getters.effectiveList.every((item) => item.selected)
    }
  },
  mutations: {
    // 加入购物车
    /**
     *
     * @param {*} state
     * @param {*} good 当前加入购物车商品
     */
    addCart (state, good) {
      /**
       * 思路:
       * 1.判断当前商品good之前如果添加过=>只增加数量,如果没加过就push进去即可
       */
      const index = state.list.findIndex(item => item.skuId === good.skuId)
      if (index > -1) {
        state.list[index].count += good.count
      } else {
        state.list.unshift(good)
      }
    },
    // 删除购物车商品
    delCart (state, good) {
      const index = state.list.findIndex(item => item.skuId === good.skuId)
      state.list.splice(index, 1)
    },
    // 商品选中(单选)
    singleCheck (state, { good, selected }) {
      /**
       * 1.找到当前单选的商品
       * 2.通过state修改
       */
      const currProd = state.list.find(item => item.skuId === good.skuId)
      currProd.selscted = selected
    },
    // 商品全选/取消
    checkAll (state, selected) {
      state.list.forEach(item => { item.selected = selected })
    },
    // 商品数量的修改
    changeCount (state, { good, count }) {
      const currProd = state.list.find(item => item.skuId === good.skuId)
      currProd.count = count
    },
    // 修改list购物车的数据
    setList (state, newList) {
      state.list = newList
    }
  },

  actions: {
    // 合并购物车商品=>当前登录人购物车=未登录存储的购物车商品+登录后存储的购物车商品
    async mergeCartAction ({ state, dispatch }) {
      /**
       * 1.判断本地是否存储购物车商品
       * 2.如果有就调用接口合并
       * 3.合并完重新获取当前登录人的购物车商品数据
       *
       */
      if (state.list.length) {
        const mergeData = state.list.map(item => {
          return { skuId: item.skuId, selected: item.selected, count: item.count }
        })
        await mergeLocalCart(mergeData)
      }
      dispatch('getCartList')
    },
    // 获取当前登录人购物车产品数据
    async getCartList ({ commit }) {
      const { result } = await findCartList()
      commit('setList', result)
    },
    // Promise封装基本写法
    /*  addCartAction ({ commit, rootState }, good) {
      return new Promise((resolve, reject) => {
        if (rootState.user.profile.token) {
          // 登录后加入购物车
        } else {
          commit('addCart', good)
          resolve('加不成功')
        }
      })
    } */
    // Promise封装异步写法
    /**
     * resolve()使用return值
     * reject()使用throw
     *
     */
    async addCartAction ({ commit, rootState, dispatch }, good) {
      if (rootState.user.profile.token) {
        // 登录后加入购物车
        /**
         * 1.调用接口入库
         * 2.调用接口获取最新的
         */
        await insertCart({ skuId: good.skuId, count: good.count })
        dispatch('getCartList')
      } else {
        commit('addCart', good)
        // resolve('加不成功')
        return '添加不成功'
      }
    },
    // 删除购物车
    async delCartAction ({ commit, rootState, dispatch }, good) {
      if (rootState.user.profile.token) {
        // 登录后加入购物车
        await deleteCart([good.skuId])
        dispatch('getCartList')
      } else {
        // 未登录
        commit('delCart', good)
      }
    },
    // 单选
    async singleCheckAction ({ commit, rootState, dispatch }, { good, selected }) {
      if (rootState.user.profile.token) {
        // 登录后加入购物车
        await updateCart({ ...good, selected })
        dispatch('getCartList')
      } else {
        // 未登录
        commit('singleCheck', { good, selected })
      }
    },
    // 全选
    async checkAllAction ({ commit, state, rootState, dispatch }, selected) {
      if (rootState.user.profile.token) {
        // 登录后加入购物车
        const ids = state.list.map(item => item.skuId)
        await checkAllCart({ selected, ids })
        dispatch('getCartList')
      } else {
        // 未登录
        commit('checkAll', selected)
      }
    },
    // 商品数量
    async changeCountAction ({ commit, rootState, dispatch }, { good, count }) {
      if (rootState.user.profile.token) {
        // 登录后加入购物车
        await updateCart({ ...good, count })
        dispatch('getCartList')
      } else {
        // 未登录
        commit('changeCount', { good, count })
      }
    }
  }
}
